package com.proxy.server.frontend.handler.request.proxy;

import com.proxy.common.constant.FieldsType;
import com.proxy.common.exception.ProxyIoException;
import com.proxy.common.packet.*;
import com.proxy.common.utils.PacketUtil;
import com.proxy.router.SQLRouteResult;
import com.proxy.server.context.AppContext;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.session.Session;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import java.nio.charset.Charset;

/**
 * Created by liufish on 16/7/24.
 */
public class ShowDatabasesProxy {

    public static void doProxy(BinaryPacket bin, Session session, SQLRouteResult result) {

        FrontendConnection connection = session.getFrontendConnection();
        try {

            int packetId = 0;

            int FIELD_COUNT = 1;
            Channel channel = connection.getChannel();
            ByteBuf buffer = channel.alloc().buffer();

            // write header
            ResultSetHeaderPacket header = new ResultSetHeaderPacket();
            header.fieldCount = FIELD_COUNT;

            header.packetId = ++packetId;
            buffer = header.writeBuffer(buffer);

            // write fields
            FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
            for (FieldPacket field : fields) {
                field = PacketUtil.getField("DATABASE", FieldsType.FIELD_TYPE_VAR_STRING);
                field.packetId = ++packetId;
                buffer = field.writeBuffer(buffer);
            }

            // write eof
            EOFPacket eof = new EOFPacket();
            eof.packetId = ++packetId;
            buffer = eof.writeBuffer(buffer);

            // write rows
            RowDataPacket row = new RowDataPacket(FIELD_COUNT);
            byte[] names = AppContext.getInstance().getFrontendProxy().getSchema().getBytes(Charset.forName(connection.getCharset()));
            row.add(names);
            row.packetId = ++packetId;
            buffer = row.writeBuffer(buffer);


            // write last eof
            EOFPacket lastEof = new EOFPacket();
            lastEof.packetId = ++packetId;
            buffer = lastEof.writeBuffer(buffer);
            connection.write(buffer);
        } catch (Exception ex) {
            throw new ProxyIoException(ex);
        }


    }


}
